//
//  VideoController.m
//  ProjectA
//
//  Created by lanouhn on 15/5/22.
//  Copyright (c) 2015年 lanouhn. All rights reserved.
//

#import "VideoController.h"
#import "RightController.h"

#import "FirstModel.h"
#import "NetWorkEngine.h"
#import "FirstCenterCell.h"
#import "LoadingTableViewCell.h"
#import "CellController.h"
#import "CellController.h"
#import "ONLY.h"
#define KURL @"http://lol.video.luckyamy.com/api/?cat=home&page=%d&ap=lolg&ver=1.1"
#define KURLSEG @"http://lol.video.luckyamy.com/api/?cat=home&type=random&p=%d&time=1408999558&ap=lolg&ver=1.1"
@interface VideoController ()<NetworkEngineDelegate>
@property (nonatomic ,retain)UISegmentedControl *seg;
//@property (nonatomic ,retain)UIBarButtonItem *left;
@property (nonatomic ,retain)UIBarButtonItem *right;
@property (nonatomic ,retain)NSMutableArray *dataSource;
@property (nonatomic ,assign)int pageNumber;
- (void)_startLoadingDataWithPage:(int)page url:(NSString *)url;//根据页码和网址下载数据
@end

@implementation VideoController
- (void)dealloc {
    [_seg release];
//    [_left release];
    [_right release];
    [_dataSource release];
    [super dealloc];
}
- (NSArray *)dataSource{
    if (!_dataSource) {
        self.dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
//- (UIBarButtonItem *)left{
//    if (!_left) {
//        self.left = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"AdSageRecmd_0_iPhone"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(handleLeftAction)];
//    }
//    return _left;
//}
- (UIBarButtonItem *)right{
    if (!_right) {
        self.right = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"history"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(handleRightAction)];
    }
    return _right;
}

- (UISegmentedControl *)seg{
    if (!_seg) {
        self.seg = [[[UISegmentedControl alloc]initWithItems:@[@"最近更新" , @"排行热播"]]autorelease];
        _seg.frame = CGRectMake(0, 0, 120, 35);
        _seg.selectedSegmentIndex = 0;
        _seg.tintColor = [UIColor colorWithRed:255 / 256.0 green:115 / 256.0 blue:115 / 255.0 alpha:1];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,[UIFont systemFontOfSize:16],NSFontAttributeName, nil];
        [_seg setTitleTextAttributes:dic forState:UIControlStateNormal];
        [_seg setTitleTextAttributes:dic forState:UIControlStateSelected];
        [self.seg addTarget:self action:@selector(handleSeg:) forControlEvents:UIControlEventValueChanged];

        
    }
    return _seg ;
}
- (void)handleSeg:(UISegmentedControl *)sender{
    if (sender.selectedSegmentIndex == 0) {
        self.pageNumber = 1;
        [self.dataSource removeAllObjects];
        [self.tableView reloadData];
        [self _startLoadingDataWithPage:self.pageNumber url:KURL];
    }
    else{
        self.pageNumber = 1;
        [self.dataSource removeAllObjects];
        [self.tableView reloadData];
         [self _startLoadingDataWithPage:self.pageNumber url:KURLSEG];
    }
   
}
- (void)_startLoadingDataWithPage:(int)page url:(NSURL *)url{
    if (self.seg.selectedSegmentIndex == 0) {
        NetworkEngine *engine = [NetworkEngine engineWithURL:[NSURL URLWithString:[NSString stringWithFormat:KURL,page]] parameters:nil delegate:self];
        [engine start];
    }else{
        NetworkEngine *engine = [NetworkEngine engineWithURL:[NSURL URLWithString:[NSString stringWithFormat:KURLSEG,page]] parameters:nil delegate:self];
        [engine start];
    }
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tableView.separatorColor = [UIColor clearColor];
    self.navigationItem.title = @"返回";
    self.navigationItem.titleView = self.seg;
    self.navigationItem.rightBarButtonItem = self.right;
//    self.navigationItem.leftBarButtonItem = self.left;
    
    [self.tableView registerClass:[FirstCenterCell class] forCellReuseIdentifier:@"FirstCenter"];
    [self.tableView registerClass:[LoadingTableViewCell class] forCellReuseIdentifier:@"LOAD"];
    
    self.refreshControl = [[[UIRefreshControl alloc]init]autorelease];
    [self.refreshControl addTarget:self action:@selector(handleRefershAction:) forControlEvents:(UIControlEventValueChanged)];
    //调用加载方法
    self.pageNumber = 1;
    
    [self _startLoadingDataWithPage:self.pageNumber url:KURL];
    //[self.refreshControl beginRefreshing];//开始刷新

}
#pragma Action
- (void)handleRefershAction:(UIRefreshControl *)sender{
    self.pageNumber = 1;
    if (self.seg.selectedSegmentIndex == 0) {
        
        [self _startLoadingDataWithPage:self.pageNumber url:KURL];
    }else{
        [self _startLoadingDataWithPage:self.pageNumber url:KURLSEG];

    }
    
}

- (void)handleRightAction{
    RightController *right = [[RightController alloc]init];
    [self.navigationController pushViewController:right animated:YES];
    [right release];
}
//- (void)handleLeftAction{}
#pragma __delegate__
- (void)networkDidFinishLoading:(NetworkEngine *)engine withInfo:(id)info {
    if (info == nil) {
        return;
    }
    [self.refreshControl endRefreshing];//结束刷新
    if (self.pageNumber == 1) {
        [self.dataSource removeAllObjects];//移除之前保存的
    }
    
    self.pageNumber ++;
    NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:info options:NSJSONReadingMutableContainers error:nil];
//    NSLog(@"%@",array);
    for (NSDictionary *dic in array) {
        FirstModel *model = [FirstModel modleWithDictionary:dic];
        [self.dataSource addObject:model];
           }
    [self.tableView reloadData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section {
    return self.dataSource.count +1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == self.dataSource.count) {
        return [tableView dequeueReusableCellWithIdentifier:@"LOAD" forIndexPath:indexPath];
    }
    FirstCenterCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FirstCenter" forIndexPath:indexPath];
    FirstModel *anModel = self.dataSource[indexPath.row];
    [cell cellWithModel:anModel temp:YES];
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 110;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    //表视图在滑动过程中将要显示单元格时会相应该方法
    if ([cell isKindOfClass:[LoadingTableViewCell class]] && self.dataSource.count == indexPath.row) {
        [(LoadingTableViewCell *)cell startLoading];
        if (self.seg.selectedSegmentIndex == 0) {
            [self _startLoadingDataWithPage:self.pageNumber url:KURL];
        }else{
           [self _startLoadingDataWithPage:self.pageNumber url:KURLSEG];
        }
        
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"gyugui");
    CellController *cellView = [[CellController alloc]init];
    cellView.model = self.dataSource[indexPath.row];
    [[ONLY creatOnly] passingValueWithContentmodel:self.dataSource[indexPath.row]];
    [self.navigationController pushViewController:cellView animated:YES];
    [cellView release];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
